import * as React from 'react';
import Cropper from 'react-cropper';
import { Button, Upload } from 'antd';
import { UploadChangeParam } from 'antd/es/upload/interface';

export interface CropUploadProps {
  onChange?(img: Blob): void;
}

class CropUpload extends React.Component<CropUploadProps, any> {
  static propTypes = {};
  private cropperRef: React.RefObject<Cropper> = React.createRef();
  private cropperInstance: Cropper;

  constructor(props: CropUploadProps) {
    super(props);
    this.state = {
      src: null,
    };
  }

  private handleFileChange = ({ file }: UploadChangeParam) => {
    const f = file as unknown as File;
    const reader = new FileReader();
    reader.onload = () => {
      this.setState({ src: reader.result });
    };
    reader.readAsDataURL(f);
  };

  getImage() {
    if (this.cropperRef.current) {
      return this.cropperInstance.getCroppedCanvas();
    }
    return null;
  }

  render() {
    return (
      <div className="ux-crop-upload">
        <Upload
          className="ux-user-personal-avatar-edit-fileSelector"
          onChange={this.handleFileChange}
          beforeUpload={() => false}
          accept="image/*"
          showUploadList={false}
          style={{ height: '100%' }}
        >
          <Button>选择图像</Button>
        </Upload>
        {this.props.children}
        <div className="ux-crop-upload-wrapper cropper-container-container">
          <div className="ux-crop-upload-cropper cropper-container">
            <Cropper
              ref={this.cropperRef as any}
              onInitialized={(instance) => {
                this.cropperInstance = instance;
              }}
              src={this.state.src}
              aspectRatio={1}
              guides={false}
              viewMode={1}
              autoCropArea={0}
              zoomable={true}
              cropBoxResizable={true}
              preview=".cropper-preview"
            />
          </div>
          <div className="ux-crop-upload-preview cropper-container">
            <div className="cropper-preview-wrapper">
              <div className="cropper-preview size-lg" />
              <div className="cropper-preview-text">180x180</div>
            </div>
            <div className="cropper-preview-wrapper size-md">
              <div className="cropper-preview size-md" />
              <div className="cropper-preview-text">150x150</div>
            </div>
            <div className="cropper-preview-wrapper">
              <div className="cropper-preview size-sm" />
              <div className="cropper-preview-text">100x100</div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

CropUpload.propTypes = {};

export default CropUpload;
